package icu.d4peng.cloud.gateway.filter;

import icu.d4peng.cloud.gateway.constant.GatewayConstant;
import icu.d4peng.cloud.gateway.exception.AuthException;
import icu.d4peng.cloud.gateway.service.HttpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author d4peng
 * @version 1.0.0
 * @date 2022-01-03 17:14
 * @description AuthFilter:认证过滤器,信息认证通过,就可以下一步操作
 */
@Configuration
public class AuthFilter implements GlobalFilter, Ordered {
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthFilter.class);

    private HttpService httpService;

    @Autowired
    public AuthFilter(HttpService httpService) {
        this.httpService = httpService;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        if (path.equals("/login")) {
            return chain.filter(exchange);
        } else {
            String token = request.getHeaders().getFirst(GatewayConstant.TOKEN_HEADER.value());
            if (StringUtils.isBlank(token)) {
                LOGGER.error("no token header");
                throw new AuthException();
            } else {
                // 验证Token是否正确,验证路由是否有权限
                request = request.mutate().header("roc-id", "").build();
                return chain.filter(exchange);
            }
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
